/*
 * Copyright (C) 2018 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xdlinkdemo.fragment;

import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.xuexiang.xaop.annotation.MainThread;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xdlink.component.channel.entity.ConnectStatusEnum;
import com.xuexiang.xdlinkdemo.R;
import com.xuexiang.xdlinkdemo.adapter.ChatMessageAdapter;
import com.xuexiang.xdlinkdemo.device.Constants;
import com.xuexiang.xdlinkdemo.device.provider.ChatClientDataProvider;
import com.xuexiang.xdlinkdemo.device.provider.OnChatListener;
import com.xuexiang.xdlinkdemo.entity.ApiEntity;
import com.xuexiang.xdlinkdemo.entity.ChatMessage;
import com.xuexiang.xdlinkdemo.entity.LoginInfo;
import com.xuexiang.xdlinkdemo.util.SettingSpUtils;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.base.XPageFragment;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.NetworkUtils;
import com.xuexiang.xutil.tip.ToastUtils;

import butterknife.BindView;
import butterknife.OnClick;

import static com.xuexiang.xdlinkdemo.device.Constants.ApiType.LOGIN;

/**
 * @author xuexiang
 * @since 2018/9/3 下午8:14
 */
@Page(name = "聊天室客户端")
public class ChatRoomClientFragment extends XPageFragment implements OnChatListener {

    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.et_send_content)
    EditText etSendContent;
    @BindView(R.id.et_server_address)
    EditText etServerAddress;

    @BindView(R.id.btn_connect)
    Button btnConnect;

    private ChatClientDataProvider mChatClient;

    private ChatMessageAdapter mChatAdapter;

    private boolean mIsConnected;
    private boolean mIsLogin;

    private LoginInfo mLoginInfo;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_chat_client;
    }

    @Override
    protected void initViews() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(mChatAdapter = new ChatMessageAdapter());
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        etServerAddress.setText(SettingSpUtils.get().getServerIP());
    }

    @Override
    protected void initListeners() {
        mChatClient = new ChatClientDataProvider(getContext());
        mChatClient.setOnChatListener(this);
    }

    @SingleClick
    @OnClick({R.id.btn_login, R.id.btn_clear, R.id.btn_send, R.id.btn_connect})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_connect:
                String address = etServerAddress.getText().toString();
                if (StringUtils.isEmpty(address)) {
                    ToastUtils.toast("请先填写服务器地址！");
                    return;
                }
                if (!NetworkUtils.isIP(address)) {
                    ToastUtils.toast("服务器地址输入不合法！");
                    return;
                }

                if (!NetworkUtils.isHaveInternet()) {
                    ToastUtils.toast("当前网络不可用！");
                    return;
                }

                btnConnect.setEnabled(false);
                SettingSpUtils.get().setServerIP(address);
                mChatClient.connect(address);
                break;
            case R.id.btn_login:
                if (!mIsConnected) {
                    ToastUtils.toast("请先连接服务器！");
                    return;
                }
                String name = etName.getText().toString();
                String password = etPassword.getText().toString();
                if (StringUtils.isEmpty(name)) {
                    ToastUtils.toast("用户名不能为空！");
                    return;
                }
                if (StringUtils.isEmpty(password)) {
                    ToastUtils.toast("密码不能为空！");
                    return;
                }

                mLoginInfo = new LoginInfo()
                        .setLoginName(name)
                        .setPassword(password);

                mChatClient.send(new ApiEntity<LoginInfo>(Constants.ApiType.LOGIN)
                        .setData(mLoginInfo));


                break;
            case R.id.btn_clear:
                mChatAdapter.clear();
                mChatAdapter.notifyDataSetChanged();
                break;
            case R.id.btn_send:
                String content = etSendContent.getText().toString();
                if (!mIsLogin) {
                    ToastUtils.toast("请先登录！");
                    return;
                }
                if (StringUtils.isEmpty(content)) {
                    ToastUtils.toast("发送内容不能为空！");
                    return;
                }

                boolean result = mChatClient.send(new ApiEntity<ChatMessage>(Constants.ApiType.SEND_MESSAGE)
                        .setData(new ChatMessage().setLoginName(mLoginInfo.getLoginName())
                                .setContent(content)));
                if (result) {
                    etSendContent.setText("");
                }
                break;
        }
    }

    @Override
    @MainThread
    public void onChatStatusChanged(ConnectStatusEnum status) {
        switch(status) {
            case CONNECT_SUCCESS:
                tvStatus.setText("已连接");
                mIsConnected = true;
                break;
            case CONNECT_FAILED:
                btnConnect.setEnabled(true);
                tvStatus.setText("已断开");
                mIsConnected = false;
                break;
            default:
                break;
        }
    }

    @Override
    @MainThread
    public void onUpdateEvent(String eventType, Object object) {
        switch(eventType) {
            case LOGIN:
                if ((boolean)object) {
                    mIsLogin = true;
                    tvStatus.setText("已登录");
                } else {
                    mIsLogin = false;
                }
                break;
            default:
                break;
        }
    }

    @Override
    @MainThread
    public void onUpdateChatMessage(ChatMessage message) {
        mChatAdapter.load(message);
    }

    @Override
    public void onDestroyView() {
        if (mChatClient != null) {
            mChatClient.disconnect();
        }
        super.onDestroyView();
    }

}
